package com.winning.ds.common.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.StringTokenizer;


/**
* @Author: nxs@winning.com.cn
* 
* @Description:   ip地址工具类
* 
* @Date: 2018-08-09 10:17:00
*
*
 **/ 
public class IPUtil {
    private static Logger logger = LoggerFactory.getLogger(IPUtil.class);


    /**
    * @Author: nxs@winning.com.cn
    * 
    * @Description:  判断是否是卫宁内网IP
    * 
    * @Date: 2018-08-09 11:01:42
    *
    *
     **/ 
    public static boolean validateIsInnerIp(String ip) {
        boolean isInner = false;
        if (ip.startsWith("127.0.0.1") || ip.startsWith("172.16.") || ip.equals("203.110.176.175")) {
            // 认证ip通过
            isInner = true;
        }
        return isInner;
    }

    /**
     * 获取客户端ip
     */
    public static String getIp(HttpServletRequest request) {

        String xip = request.getHeader("x-forwarded-for");
        String ip = request.getHeader("X-Real-IP");


        if (!checkIP(ip)) {
            ip = request.getHeader("REMOTE-HOST");
        }

        if (!checkIP(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (!checkIP(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (!checkIP(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (!checkIP(ip)) {
            ip = request.getRemoteAddr();
        }

        // 多级反向代理
        if (null != ip && !"".equals(ip.trim())) {
            StringTokenizer st = new StringTokenizer(ip, ",");
            if (st.countTokens() > 1) {
                logger.error("getip StringTokenizer  " + ip);
                return st.nextToken();
            }
        }

        if (!ip.equals(xip)) {
            logger.error("getipne   X-Real-IP  " + ip + "    ,x-forwarded-for " + xip);
        }
        if("0:0:0:0:0:0:0:1".equals(ip)){
            ip="127.0.0.1";
        }
        return ip;
    }

    
    /**
    * @Author: nxs@winning.com.cn
    * 
    * @Description:  验证ip地址格式是否正确
    * 
    * @Date: 2018-08-09 11:20:07
    *
    *
     **/ 
    private static boolean checkIP(String ip) {
        if (StringUtils.isNotBlank(ip) && ip.split("\\.").length == 4) {
            return true;
        }
        return false;
    }

}